package com.example.sqlitedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // 数据库帮助工具
    private MyDBHelper myDBHelper = new MyDBHelper(this, "db_test", null, 1);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*insert("张三", "11111111111");
        insert("李四", "11111111112");
        insert("王五", "11111111113");
        insert("赵六", "11111111114");*/
//        delete("11111111113");
        update(1, "张三丰");
        query();

    }

    // 添加数据
    private void insert(String name, String phone) {
        SQLiteDatabase writableDatabase = myDBHelper.getWritableDatabase();
        // 数据
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("phone", phone);
        // 插入
        writableDatabase.insert(MyDBHelper.TEST_TABLE, null, contentValues);
    }

    // 删除数据
    private void delete(String phone) {
        myDBHelper.getWritableDatabase().delete(MyDBHelper.TEST_TABLE, "phone=?", new String[]{phone});
    }

    // 修改数据
    private void update(Integer id, String name) {
        SQLiteDatabase readableDatabase = myDBHelper.getReadableDatabase();
        // 修改的数据
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        readableDatabase.update(MyDBHelper.TEST_TABLE, contentValues, "id=?", new String[]{id.toString()});
    }

    // 删除全部
    private void clear() {
        myDBHelper.getWritableDatabase().delete(MyDBHelper.TEST_TABLE, null, null);
    }

    // 查询数据
    private void query() {
        String result = "";
        Cursor cursor = myDBHelper.getReadableDatabase().query(MyDBHelper.TEST_TABLE, null, null, null, null, null, null);
        if (cursor.getCount() == 0) {
            result = "没有数据";
        } else {
            result = "";
            while (cursor.moveToNext()) {
                result += "{id=" + cursor.getInt(0) +
                        ", 姓名=" + cursor.getString(1) +
                        ", 手机=" + cursor.getString(2) + "}\n";
            }
        }
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }

}